package com.orcs.leefei.component;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.orcs.leefei.utils.R;

/**
 * Created by Administrator on 2017/3/13.
 */

public class RatioView extends View {
    private final MeasureUtils.Spec mMeasureSpec = new MeasureUtils.Spec();
    private float mAspectRatio = 0;

    public RatioView(Context context) {
        this(context, null);
    }

    public RatioView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RatioView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, @Nullable AttributeSet attrs) {
        if (isInEditMode()) {
            return;
        }

        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(
                    attrs,
                    R.styleable.RatioView);
            try {
                mAspectRatio = a.getFloat(R.styleable.RatioView_viewAspectRatio, 0);
            } finally {
                if (a != null) {
                    a.recycle();
                }
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mMeasureSpec.width = widthMeasureSpec;
        mMeasureSpec.height = heightMeasureSpec;
        MeasureUtils.updateMeasureSpec(
                mMeasureSpec,
                mAspectRatio,
                getLayoutParams(),
                getPaddingLeft() + getPaddingRight(),
                getPaddingTop() + getPaddingBottom());
        setMeasuredDimension(mMeasureSpec.width, mMeasureSpec.height);
    }


}
